package indi.wshape1.takeawaydeliveryinfo.filter;

import indi.wshape1.takeawaydeliveryinfo.util.ConnectionUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * @author Wshape1
 * @create 2022-12-09 18:35
 */

@WebFilter(filterName = "MyFilter", value = {"/delete", "/change", "/more"})
public class MyFilter extends HttpFilter {
    @Override
    public void doFilter(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            ConnectionUtil.getConnection().setAutoCommit(false);    // 开启事务
            filterChain.doFilter(servletRequest, servletResponse);  // 放行
            if (!ConnectionUtil.getConnection().getAutoCommit())
                ConnectionUtil.getConnection().commit();            // 提交事务
            ConnectionUtil.closeConnection();
        } catch (Exception e) {     // 发生意外

            PrintWriter writer = servletResponse.getWriter();
            //  给请求端返回 错误代码
            String servletPath = servletRequest.getServletPath().substring(1);
            if ("delete".equals(servletPath))
                writer.print("[{\"state\": \"0\"}]");
            else if ("more".equals(servletPath))
                writer.print(2);
            else
                writer.print(0);
            writer.close();


            try {
                ConnectionUtil.getConnection().rollback();  // 回滚事务
                ConnectionUtil.closeConnection();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}
